package com.itheima.reggie.controller;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.itheima.reggie.common.R;
import com.itheima.reggie.config.MyConfig;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wx")
public class WxPayController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/notifyAll")
    public void notfyAll(HttpServletRequest request, HttpServletResponse response) throws Exception {
       //流数据IO
        //告诉商家,那个订单支付成功
        System.out.println("我接受到回调消息了");
        String string = convertToString(request.getInputStream());
        //把xml 请求参数转换成Map
        Map<String, String> map = WXPayUtil.xmlToMap(string);
        //1.支付的订单号  那个订单支付的
        //2.微信订单号(流水号)   后期退款需要用到的
        String transaction_id = map.get("transaction_id");
        //3.return_code  代表是否返回的是成功
        String return_code = map.get("return_code");
        if (return_code.equals("SUCCESS")){//代表支付成功
            //4.根据订单号,查询微信端的支付状态
            String out_trade_no = map.get("out_trade_no");
            //调用微信的查询订单接口来查询订单是否真的支付成功
            boolean flag = checkOrderStatus(out_trade_no);
            if (flag){//代表真的支付了,修改订单状态为已支付即可
                orderService.updateStatus(out_trade_no,transaction_id);

                //给微信支付一个成功的响应
                response.setContentType("text/xml");
                String data = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                response.getWriter().write(data);

            }
        }

        //获取支付成功的订单  然后修改数据的订单状态为已支付



    }


    private boolean checkOrderStatus(String out_trade_no) throws Exception {
        WXPay wxPay = new WXPay(new MyConfig());

        HashMap<String, String> map = new HashMap<>();
        map.put("out_trade_no",out_trade_no);
        Map<String, String> responseMap = wxPay.orderQuery(map);
        String trade_status = responseMap.get("trade_status");
        return trade_status.equals("SUCCESS");
    }

    /**
     * 输入流转换为xml字符串
     * @param inputStream
     * @return
     */
    public static String convertToString(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inputStream.close();
        String result = new String(outSteam.toByteArray(), "utf-8");
        return result;
    }
}
